package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 发送设备设置预置
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetPreset implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 发送器序号
         */
        private Integer prcIndex;

        /**
         * 屏幕分组数
         */
        private Integer groupIndex;

        /**
         * 预置参数序号
         */
        private Integer presetIndex;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 结果
         */
        private Boolean result;
    }

    private InputMsg inputMsg;
    private OutputMsg outputMsg;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.SetPreset.InputMsg.Builder inputMsgBuilder =
                CompleteInstruction.SetPreset.InputMsg.newBuilder();
        SetPreset.InputMsg thisInput = this.getInputMsg();
        inputMsgBuilder.setPrcIndex(thisInput.getPrcIndex());
        inputMsgBuilder.setGroupIndex(thisInput.getGroupIndex());
        inputMsgBuilder.setPresetIndex(thisInput.getPresetIndex());

        final CompleteInstruction.SetPreset.Builder builder =
                CompleteInstruction.SetPreset.newBuilder();
        builder.setInput(inputMsgBuilder);
        return builder.build().toByteString();
    }

    @Override
    public SetPreset byteConvertObject(ByteString bytes) {
        CompleteInstruction.SetPreset setPreset = null;
        try {
            setPreset = CompleteInstruction.SetPreset.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setPreset)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        SetPreset.OutputMsg outputMsg = new SetPreset.OutputMsg();
        outputMsg.setResult(setPreset.getOutput().getResult());
        this.setOutputMsg(outputMsg);
        return this;
    }
}

